package com.qf.fmall2202.user.interception;

import com.qf.fmall2202.exception.QfException;
import com.qf.fmall2202.utils.CommonConstants;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 检查请求中的token是否合法
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("token");
        JwtParser parser = Jwts.parser();
        parser.setSigningKey(CommonConstants.JWT_SECRET_KEY);
        try {
            parser.parse(token);
            return true;
        } catch (ExpiredJwtException e) {
            throw new QfException("登录过期，请重新登录！");
        } catch (UnsupportedJwtException e) {
            throw new QfException("Tonken不合法，请自重！");
        } catch (Exception e) {
            throw new QfException("请重新登录！");
        }
    }
}
